const { friendUrl, searchUrl } = require('./enum')
const puppeteer = require('puppeteer')

async function getHtmlWithPuppeteer(url) {
    console.log(url)
    //公司笔记本地址
    // const  executablePath= 'C:/Users/wangyongjie/AppData/Local/Google/Chrome/Application/chrome'

    //家里台式地址
    const executablePath = 'C:/Program Files/Google/Chrome/Application/chrome'

    // const browser = await puppeteer.launch({
    //     headless: 'new',
    //     executablePath,
    // })
    /**
     * 自动获取geogle地址
     * */
    const browser = await puppeteer.launch({
        headless: 'new',
    })

    /**
     * 启动调试
     * */
    // const browser = await puppeteer.launch({
    //     headless: false,
    //     executablePath,
    //     args: ['--auto-open-devtools-for-tabs'], // 自动打开调试窗口
    // })
    let result = {}
    try {
        const page = await browser.newPage()

        await page.setDefaultNavigationTimeout(120 * 1000)
        // 访问页面
        await page.goto(url, { waitUntil: 'networkidle2' })

        // 获取页面高度
        const pageHeight = await page.evaluate(() => {
            return Math.max(
                document.body.scrollHeight,
                document.body.offsetHeight,
                document.documentElement.clientHeight,
                document.documentElement.scrollHeight,
                document.documentElement.offsetHeight,
            )
        })

        // 设置视口大小，避免显示不全时，某些元素延迟加载，导致无法获取
        await page.setViewport({
            width: 1200,
            height: pageHeight,
        })

        await page.evaluate(async () => {
            /**
             * 这些方法必须定义到window中，不然下个evaluate事件获取不到
             * */
            window.getBaseInfo = () => {
                let baseInfoDom = document.querySelector('.lemma-summary.J-summary')
                if (!baseInfoDom) {
                    baseInfoDom = document.querySelector('.J-summary')
                }
                const baseInfo = baseInfoDom?.innerText
                return baseInfo
            }

            window.getCoverUrl = () => {
                let coverDom = document.querySelector('.layout.lemmaWgt-posterBg')
                if (!coverDom) {
                    coverDom = document.querySelector('[class^="posterBg_"]')
                }
                let str = ''
                if (coverDom) {
                    let temp = getComputedStyle(coverDom).backgroundImage
                    str = temp.substring(5, temp.length - 2)
                }
                return str
            }

            window.getPosterArr = () => {
                let domResult,
                    result = []
                // 尝试1
                domResult = document.querySelector('.marquee-canvas.J-marquee-canvas')
                if (!domResult) {
                    domResult = document.querySelector('[class^="swiperUl_"]')
                }
                if (domResult) {
                    domResult.querySelectorAll('img').forEach((item) => {
                        if (item.src) {
                            result.push(item.src)
                        }
                    })
                    if (!result.length) {
                        domResult.querySelectorAll('a').forEach((item) => {
                            if (item.href) {
                                result.push(item.href)
                            }
                        })
                    }
                }

                return result
            }
        })

        const baseInfo = await page.evaluate(async () => {
            return getBaseInfo()
        })
        const coverUrl = await page.evaluate(async () => {
            return getCoverUrl()
        })
        let posterUrlArr = await page.evaluate(async () => {
            return getPosterArr()
        })
        if (!posterUrlArr?.length) {
            console.log('执行自动滚动事件')
            // 滚动到底部
            await page.evaluate(() => {
                window.scrollTo(0, document.body.scrollHeight)
            })
            // 等待一段时间，确保页面加载完成
            await page.waitForTimeout(100)
            posterUrlArr = await page.evaluate(async () => {
                return getPosterArr()
            })
        }

        result = { coverUrl, baseInfo, posterUrlArr }
    } catch (e) {
        console.log(url)
        console.log(e)
    }
    // 关闭浏览器
    await browser.close()
    return result
}

module.exports = {
    getHtmlWithPuppeteer,
}
